package com.example.serialization.serializable.persistence;

import java.io.*;

public class SerializableDemo {
    public static void main(String[] args) {
        // 1. 创建对象并初始化
        User user = new User("Alice", 25, "secret");
        System.out.println("[原始对象] " + user);

        // 2. 序列化对象到文件
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.ser"))) {
            oos.writeObject(user);
            System.out.println("[序列化完成] 对象已写入文件 user.ser");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 3. 反序列化对象
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.ser"))) {
            User deserializedUser = (User) ois.readObject();
            System.out.println("[反序列化完成] 从文件读取的对象: " + deserializedUser);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

class User implements Serializable {
    // 显式声明 serialVersionUID，避免类修改后反序列化失败
    private static final long serialVersionUID = 1L;

    private String name;
    private int age;
    private transient String password; // transient 字段不会被序列化

    public User(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }

    // 自定义序列化逻辑（可选）
    private void writeObject(ObjectOutputStream oos) throws IOException {
        System.out.println("[自定义序列化] 正在序列化字段: name=" + name + ", age=" + age);
        oos.defaultWriteObject(); // 默认序列化非 transient 字段
    }

    // 自定义反序列化逻辑（可选）
    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        ois.defaultReadObject(); // 默认反序列化非 transient 字段
        System.out.println("[自定义反序列化] 已读取字段: name=" + name + ", age=" + age);
        password = "default"; // 手动初始化 transient 字段
    }

    @Override
    public String toString() {
        return "User{name='" + name + "', age=" + age + ", password='" + password + "'}";
    }
}